'use strict';

const Service = require('egg').Service;
const City = require('../model/city');
const TravelNote = require('../model/travelNote');
const TravelPlan = require('../model/travel_plan');
const User = require('../model/user');
const { Op } = require('sequelize');

class HomeService extends Service {
  async getHotCities(limit = 6) {
    try {
      const cities = await City.findAll({
        where: {
          recommendations: {
            [Op.gt]: 0
          }
        },
        order: [['recommendations', 'DESC']],
        limit,
        attributes: ['id', 'name', 'image', 'description', 'rating', 'views', 'recommendations']
      });

      return cities.map(city => ({
        id: city.id,
        name: city.name,
        image: city.image,
        description: city.description,
        visitCount: city.views || Math.floor(city.recommendations * 1.5),
        rating: city.rating
      }));
    } catch (error) {
      this.ctx.logger.error('获取热门城市失败:', error);
      throw error;
    }
  }

  async getHotNotes(limit = 6) {
    try {
      const notes = await TravelNote.findAll({
        where: {
          status: 'approved',
          visibility: 'public'
        },
        order: [
          ['is_top', 'DESC'],           // 置顶权重最高
          ['favorite_count', 'DESC'],   // 收藏数（推荐数）
          ['view_count', 'DESC'],       // 浏览量
          ['like_count', 'DESC']        // 点赞数
        ],
        limit,
        include: [
          {
            model: User,
            as: 'author',
            attributes: ['id', 'username', 'nickname', 'avatar']
          }
        ]
      });

      return notes.map(note => this._formatNote(note));
    } catch (error) {
      this.ctx.logger.error('获取热门游记失败:', error);
      throw error;
    }
  }

  async getHotPlans(limit = 6) {
    try {
      const plans = await TravelPlan.findAll({
        where: {
          status: 'approved',
          is_public: true
        },
        order: [
          ['is_top', 'DESC'],      // 置顶优先
          ['created_at', 'DESC']   // 最新的
        ],
        limit,
        include: [
          {
            model: City,
            as: 'city',
            attributes: ['id', 'name', 'image']
          }
        ]
      });

      return plans.map(plan => this._formatPlan(plan));
    } catch (error) {
      this.ctx.logger.error('获取热门旅行计划失败:', error);
      throw error;
    }
  }

  async getFeaturedCommunity(limit = 4) {
    try {
      const posts = await TravelNote.findAll({
        where: {
          status: 'approved',
          visibility: 'public'
        },
        order: [
          ['is_top', 'DESC'],       // 置顶权重最高
          ['view_count', 'DESC'],   // 按浏览量排序
          ['like_count', 'DESC']    // 次要排序：点赞数
        ],
        limit,
        include: [
          {
            model: User,
            as: 'author',
            attributes: ['id', 'username', 'nickname', 'avatar']
          }
        ]
      });

      return posts.map(post => this._formatCommunityPost(post));
    } catch (error) {
      this.ctx.logger.error('获取社区精选失败:', error);
      throw error;
    }
  }

  _formatNote(note) {
    if (!note) return null;

    // 解析图片数组
    let galleryImages = [];
    try {
      if (note.gallery_images) {
        galleryImages = typeof note.gallery_images === 'string'
          ? JSON.parse(note.gallery_images)
          : note.gallery_images;
      }
    } catch (e) {
      galleryImages = [];
    }

    // 解析标签
    let tags = [];
    try {
      if (note.tags) {
        tags = typeof note.tags === 'string' ? JSON.parse(note.tags) : note.tags;
      }
    } catch (e) {
      tags = [];
    }

    return {
      id: note.id,
      title: note.title,
      cover: note.cover_image,
      summary: note.description || note.content?.substring(0, 100),
      author: note.author?.nickname || note.author?.username || '匿名用户',
      avatar: note.author?.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      viewCount: note.view_count || 0,
      likeCount: note.like_count || 0,
      commentCount: note.comment_count || 0,
      city: note.city,
      tags,
      images: galleryImages,
      createTime: note.published_at || note.created_at
    };
  }

  _formatPlan(plan) {
    if (!plan) return null;

    // 解析每日计划
    let dailyPlans = [];
    try {
      if (plan.daily_plans) {
        dailyPlans = typeof plan.daily_plans === 'string'
          ? JSON.parse(plan.daily_plans)
          : plan.daily_plans;
      }
    } catch (e) {
      dailyPlans = [];
    }

    return {
      id: plan.id,
      title: plan.title,
      cover: plan.cover_image,
      description: plan.description,
      days: plan.days,
      city: plan.city?.name || '未知',
      cityImage: plan.city?.image,
      startDate: plan.start_date,
      tags: ['旅行计划', plan.city?.name].filter(Boolean),
      viewCount: Math.floor((plan.id * 127) % 500), // 模拟浏览量
      favoriteCount: Math.floor((plan.id * 73) % 200) // 模拟收藏数
    };
  }

  _formatCommunityPost(post) {
    if (!post) return null;

    // 解析图片数组
    let images = [];
    try {
      if (post.gallery_images) {
        images = typeof post.gallery_images === 'string'
          ? JSON.parse(post.gallery_images)
          : post.gallery_images;
      }
    } catch (e) {
      images = [];
    }

    return {
      id: post.id,
      title: post.title,
      content: post.description || post.content?.substring(0, 150),
      author: post.author?.nickname || post.author?.username || '匿名用户',
      avatar: post.author?.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      images: images.slice(0, 3),
      likeCount: post.like_count || 0,
      commentCount: post.comment_count || 0,
      createTime: this._formatTime(post.published_at || post.created_at)
    };
  }

  _formatTime(dateStr) {
    if (!dateStr) return '';

    const date = new Date(dateStr);
    const now = new Date();
    const diff = now - date;

    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;

    return date.toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit'
    });
  }
}

module.exports = HomeService;

